import React from 'react';
import { inject, observer } from 'mobx-react';
import { IPage, IPageState, defaultPageState } from '../../types';
import { Box, BoxItem, PageHeader, FormBoxSearch, InputNumber, Button } from '../../component/pc/antd';
import { Table } from '../../component/project';
import { createColumns } from './config';
import { table } from '../../api/request';

const initialSearch = {
  weight: 1,
};

@inject('store')
@observer
export default class Tables extends React.Component<IPage, IPageState> {
  columns = createColumns(this); // 数据列配置
  currentKey = 'root'; // 分页key，用于储存当前分页
  form: any;

  state = {
    ...defaultPageState,
    search: initialSearch,
  };

  componentDidMount() {
    this.props.store!.user.onLogin(() => {
      this.getList();
    });
  }

  getList = async () => {
    this.setState({ loading: '加载列表' });
    const { keys } = this.props.store!.view;
    const state = { loading: false, data: [], total: 0 };
    const res = await table.getList({
      pageNum: keys[this.currentKey] || 1,
      pageSize: keys.pageSize,
      ...this.state.search,
    });
    if (res.ok) {
      state.data = res.data.list;
      state.total = res.data.total;
    }
    this.setState(state);
  };

  onSubmit = async (err: any, value: any) => {
    if (err) return;
    this.setState({ search: value }, this.getList);
  };

  reset = () => {
    this.form.resetFields();
    this.setState({ search: initialSearch }, this.getList);
  };

  render() {
    const { loading, data, total } = this.state;
    return (
      <Box loading={loading}>
        <BoxItem>
          <PageHeader title="表格页面">
            <FormBoxSearch onSubmit={this.onSubmit} onForm={form => (this.form = form!)}>
              {ValueItem => (
                <>
                  <ValueItem label="数据源ID" name="dataSourceId" inputProps={{ placeholder: '请输入数据源ID' }} />
                  <ValueItem
                    label="数据源名称"
                    name="dataSourceName"
                    inputProps={{ placeholder: '请输入数据源名称' }}
                  />
                  <ValueItem label="重要性" name="weight" initialValue={initialSearch.weight}>
                    <InputNumber placeholder="不限" />
                  </ValueItem>
                  <ValueItem>
                    <Button htmlType="submit">查询</Button>
                    <Button type="default" onClick={this.reset}>
                      重置
                    </Button>
                  </ValueItem>
                </>
              )}
            </FormBoxSearch>
          </PageHeader>
        </BoxItem>
        <BoxItem>
          <Table
            columns={this.columns}
            currentKey={this.currentKey}
            dataSource={data}
            total={total}
            onChange={(page: any) => {
              console.log(page);
              this.getList();
            }}
          />
        </BoxItem>
      </Box>
    );
  }
}
